package dk.lector;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import dk.lector.domain.UserFacade;

public class LoginActivity extends BaseActivity {
	private String TAG = this.getClass().getSimpleName();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);
		
		final EditText username = (EditText) findViewById(R.id.Username);
		final EditText password = (EditText) findViewById(R.id.Password);
		final TextView output = (TextView) findViewById(R.id.output);

		// DEBUG
		username.setText("PSL");
		password.setText("1234");

		findViewById(R.id.buttoncancel).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View view) {
						Intent intent = new Intent(Intent.ACTION_MAIN);
						intent.addCategory(Intent.CATEGORY_HOME);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
					}
				});

		findViewById(R.id.buttonclear).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View view) {
						username.setText("");
						password.setText("");
					}
				});

		findViewById(R.id.buttonlogin).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View arg0) {

						registerReceiver(new BroadcastReceiver() {

							@Override
							public void onReceive(Context context, Intent intent) {
								unregisterReceiver(this);
								boolean result = intent.getBooleanExtra(
										"result", false);
								if (result) {
									output.setVisibility(View.VISIBLE);
									output.setText(getString(R.string.login_onSuccess_text));
									finish();
								} else {
									output.setVisibility(View.VISIBLE);
									output.setText(getString(R.string.login_onFailure_text));
								}

							}
						}, new IntentFilter("ts.core.action.LOGIN_RESULT"));

						login(username, password, output);

					}
				});
	}

	private void login(EditText username, EditText password, TextView output) {
		output.setText(getString(R.string.login_pleaseWait_text));
		UserFacade.login(this, username.getText().toString(), password
				.getText().toString());
	}
		
}
	
	

